import json
import httpx
import asyncio
from asgiref.sync import sync_to_async
from django.shortcuts import redirect
from django.http import HttpResponseRedirect, JsonResponse


from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view

from openapi.serializers import PaymentSeralizer
from openapi.models import Store, Payment
from openapi.utils import SignRSA, aes_decrypt, aes_encrypt

# Create your views here.


@api_view(['POST'])
def openapi(request):
    ''''
        sign、iv和store_id都是明文传输
        除了sign和iv, 其他属性进行了签名。
    '''
    data = request.data.copy().dict()
    print(data)
    # 无需参与AES解密
    store_id = data.pop("stone_app_id", None)
    sign = data.pop("sign")
    iv = data.pop("iv")
    if store_id is None:
        return Response({"detail": "缺少商店号"},status.HTTP_400_BAD_REQUEST)
    store = Store.objects.get(id=store_id)
    aes_key = store.aes_key
    data = aes_decrypt(data, aes_key, iv)

    # 对除了sign和iv的明文签名
    data["stone_app_id"] = store_id
    data["sign"] = sign
    print(data)
    stone_sign_RSA = SignRSA(store.store_public_key, store.stonepay_private_key, data)
    if not stone_sign_RSA.rsa2verify():
        return Response({"detail": "签名验证失败"},status.HTTP_400_BAD_REQUEST)
    out_order_id = data.get("out_order_id", None)
    total_amount = data.get("total_amount", None)
    notify_url = data.get("notify_url", None)
    return_url = data.get("return_url", None)
    time_stamp = data.get("time_stamp", None)
    payment = Payment.objects.create (store=store, out_order_id=out_order_id, time_stamp=time_stamp,
                                     notify_url=notify_url, return_url=return_url, total_amount=total_amount,
                                     status="S")
    payment_dict = dict(PaymentSeralizer(payment).data)
    payment_dict["stone_app_id"] = payment_dict.pop("store")

    # AES 加密，除了stone_app_id, sign 和 iv
    payment_aes_dict = payment_dict
    iv, payment_aes_dict = aes_encrypt(payment_aes_dict, aes_key)
    payment_aes_dict["stone_app_id"] = store_id
    payment_aes_dict["sign"] = stone_sign_RSA.rsa2sign(payment_dict)
    payment_aes_dict["iv"] = iv

    # 发送异步请求到notify_url
    asyncio.run(get_notify(payment_aes_dict, notify_url))
    # get_notify(payment_aes_dict, notify_url)
    return redirect(return_url, permanent=True)




# def get_notify(params, notify_url):
#     print(params)
#     r = httpx.post(notify_url, json=params)
#     print(r.text)

async def get_notify(params, notify_url):
    async with httpx.AsyncClient() as client:
        r = await client.post(notify_url, json=params)
    # print(r.content)
